import {
  DrawerForm,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import React from 'react';
import { useModel } from 'umi';

import ProFormMutiLangText from '@/components/ProFormMutiLangText';

import { TagTypeOptions } from '@/services/consts';

type FormProps = {
  visible: boolean;
  defaultTagType: string | undefined;
  defaultProductId: number | undefined;
  current: API.TagModel | undefined;
  onCancel: () => void;
  onSubmit: (values: API.TagModel) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const {
    visible,
    defaultTagType,
    defaultProductId,
    current,
    onCancel,
    onSubmit,
  } = props;
  if (!visible) {
    return null;
  }

  let defaultCurrent: Partial<API.TagModel> | undefined = undefined;
  if (!current) {
    defaultCurrent = {
      type: defaultTagType,
      mutiLang: false,
      sort: 1,
      status: true,
      productId: defaultProductId,
    };
  }

  const { getProductOptions } = useModel('useGlobalModel', (model) => ({
    getProductOptions: model.getProductOptions,
  }));

  const productOptions = getProductOptions(true);

  return (
    <DrawerForm<API.TagModel>
      open={visible}
      autoFocusFirstInput
      width={640}
      title={`${current ? '编辑' : '添加'}标签`}
      initialValues={current ? current : defaultCurrent}
      //preserve={false}
      //trigger={<>{children}</>}
      onFinish={onSubmit}
      drawerProps={{
        onClose: onCancel,
        //destroyOnClose: true,
        maskClosable: false,
      }}
    >
      <ProFormSelect
        name="type"
        label="类型"
        options={TagTypeOptions}
        rules={[{ required: true, message: '请选择类型' }]}
      />
      <ProFormSelect name="productId" label="产品" options={productOptions} />
      <ProFormText
        name="name"
        label="名称"
        rules={[{ required: true, message: '请输入名称' }]}
        placeholder="请输入名称"
      />
      <ProFormDependency name={['productId', 'mutiLang']}>
        {({ productId, mutiLang }) => {
          if (productId) {
            return (
              <>
                <ProFormSwitch name="mutiLang" label="多语言" />
                {mutiLang && <ProFormMutiLangText productId={productId} />}
              </>
            );
          }

          return null;
        }}
      </ProFormDependency>
      <ProFormDigit
        name="sort"
        label="排序"
        wrapperCol={{ span: 4 }}
        min={0}
        max={9999}
      />
      <ProFormDigit
        name="sort2"
        label="排序2"
        wrapperCol={{ span: 4 }}
        min={0}
        max={9999}
      />
      <ProFormSwitch name="status" label="状态" />
      <ProFormTextArea name="remark" label="备注" />
    </DrawerForm>
  );
};

export default Form;
